﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using BattleThis.Helpers;
using BattleThis.Core;
using System.Web.Mvc;

namespace BattleThis
{
	public static class HtmlContextBaseExtensions
	{
		public const string GameContextKey = "GameContext";

		/// <summary>
		/// Determines whether [has game context] [the specified HTTP context].
		/// </summary>
		/// <param name="httpContext">The HTTP context.</param>
		/// <returns>
		///   <c>true</c> if [has game context] [the specified HTTP context]; otherwise, <c>false</c>.
		/// </returns>
		public static bool HasGameContext( this HttpContextBase httpContext ) 
		{
			return httpContext.Session[ GameContextKey ] != null;
		}

		/// <summary>
		/// Gets the game context.
		/// </summary>
		/// <param name="httpContext">The HTTP context.</param>
		/// <returns></returns>
		public static GameContext GetGameContext( this HttpContextBase httpContext )
		{
			return (GameContext)httpContext.Session[ GameContextKey ];
		}

		/// <summary>
		/// Sets the game context.
		/// </summary>
		/// <param name="httpContext">The HTTP context.</param>
		/// <param name="gameContext">The game context.</param>
		public static void SetGameContext( this HttpContextBase httpContext, GameContext gameContext )
		{
			if( gameContext == null )throw new ArgumentNullException( "gameContext" );

			httpContext.Session.Add( GameContextKey, gameContext);
		}

		/// <summary>
		/// Gets the widgets.
		/// </summary>
		/// <param name="httpContext">The HTTP context.</param>
		/// <returns></returns>
		public static List<IWidget> GetWidgets(this HttpContextBase httpContext)
		{ 
			if(!httpContext.Items.Contains("Widgets"))
			{
				httpContext.Items.Add( "Widgets", new List<IWidget>() );
			}

			return (List<IWidget>) httpContext.Items[ "Widgets" ];
		}

		/// <summary>
		/// Gets the repository of the Type T.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="httpContext">The HTTP context.</param>
		/// <returns></returns>
		public static IRepository<T> GetRepository<T> ( this HttpContextBase httpContext ) where T:class
		{
			return	DependencyResolver.Current.GetService<IRepository<T>>();
		}

	}
}